package com.example.rockscissorspapergame.dialog;

import com.example.rockscissorspapergame.ResourceTable;
import com.example.rockscissorspapergame.utils.DeviceUtils;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.distributedschedule.interwork.DeviceInfo;

import java.util.ArrayList;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

public class DeviceDialog extends CommonDialog {

    /**
     * 圆角矩形圆角半径
     */
    private final static int RADIO_SIZE = 10;

    private final List<DeviceInfo> mDeviceList = new ArrayList<>();

    private final DeviceSelectListener mDeviceSelectListener;

    private final Context mContext;

    public DeviceDialog(Context context, DeviceSelectListener deviceSelectListener) {
        super(context);
        this.mContext = context;
        this.mDeviceSelectListener = deviceSelectListener;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        // 初始化设备列表
        initDeviceList();
        // 初始化界面布局
        Component rootView = LayoutScatter.getInstance(mContext).parse(
                ResourceTable.Layout_dialog_device, null, false);
        // 初始化列表组件
        ListContainer listContainer = (ListContainer) rootView.findComponentById(ResourceTable.Id_list_container_device);
        BaseItemProvider deviceItemProvider = new DeviceItemProvider(mContext, mDeviceList, ResourceTable.Layout_item_device);
        listContainer.setItemProvider(deviceItemProvider);
        // 设置列表项点击监听
        listContainer.setItemClickedListener((listContainer1, component, i, l) -> {
            if (mDeviceSelectListener != null) {
                mDeviceSelectListener.onDeviceSelected(mDeviceList.get(i));
                hide();
            }
        });
        // 初始化取消按钮
        Button buttonCancel = (Button) rootView.findComponentById(ResourceTable.Id_operate_no);
        // 设置按钮点击监听
        buttonCancel.setClickedListener(component -> hide());
        // 设置对话框尺寸
        setSize(MATCH_PARENT, MATCH_CONTENT);
        // 设置对话框位置
        setAlignment(LayoutAlignment.CENTER);
        // 设置对话框边框的圆角半径
        setCornerRadius(RADIO_SIZE);
        // 设置对话框背景为透明
        setTransparent(true);
        // 设置对话框界面布局
        setContentCustomComponent(rootView);
    }

    private void initDeviceList() {
        List<DeviceInfo> deviceInfoList = DeviceUtils.getRemoteDeviceList();
        mDeviceList.clear();
        mDeviceList.addAll(deviceInfoList);
    }
}
